package ch.exm.storm.query.relational;

import java.util.Collection;
import java.util.List;

import ch.exm.storm.conditions.Condition;
import ch.exm.storm.log.Logger;
import ch.exm.storm.query.AbstractQueryPlan;
import ch.exm.storm.query.selection.EvaluatedRelationalSelection;

public abstract class AbstractRelationalQueryPlan extends AbstractQueryPlan implements RelationalQueryPlan {

	private String relationalStatement;
	public String getRelationalStatement() {
		return relationalStatement;
	}
	public void setRelationalStatement(String relationalStatement) {
		this.relationalStatement = relationalStatement;
	}
	
	@Override
	public String toString() {
		return relationalStatement + (postQueryCondtion == null ? "" : "; post condition: " + postQueryCondtion);
	}
	
	// ////////////////////////////////////////////////////////////////////////
	// /// PostConditions
	// ////////////////////////////////////////////////////////////////////////
	
	private Condition postQueryCondtion;
	public Condition getPostQueryCondtion() {
		return postQueryCondtion;
	}
	public void setPostQueryCondtion(Condition postQueryCondtion) {
		this.postQueryCondtion = postQueryCondtion;
	}

	protected Collection<?> applyPostConditions(Collection<?> queryResult) {
		if (postQueryCondtion == null) return queryResult;
		
		if (Logger.isInfoEnabledFor(this)) {
			StringBuilder sb = new StringBuilder("A post query condition evaluation is needed! Change the data model to allow to execute this query in a full relational way\n");
			sb.append("\tApplying post query condition: ").append(postQueryCondtion);
			Logger.info(this, sb.toString());
		}
		
		return applyConditions(queryResult, postQueryCondtion);
	}
	
	// ////////////////////////////////////////////////////////////////////////
	// /// PostSelections
	// ////////////////////////////////////////////////////////////////////////
	
	private EvaluatedRelationalSelection postSelection;
	public EvaluatedRelationalSelection getPostSelection() {
		return postSelection;
	}
	public void setPostSelection(EvaluatedRelationalSelection postSelection) {
		this.postSelection = postSelection;
	}
	
	protected Collection<?> applyPostSelections(Collection<?> queryResult) {
		if (postSelection == null) return queryResult;
		Logger.info(this, "Applying post selection: " + postSelection);
		return postSelection.applySelectionOn(queryResult);
	}
}
